import 'dart:async';
import 'dart:collection';
import 'package:df/page/splash/splash_page.dart';
import 'package:df/page/web/js_callback.dart';
import 'package:df/page/web/permission_key.dart';
import 'package:df/page/web/web_constant.dart';
import 'package:df/page/web/web_page.dart';
import 'package:df/utils/logger_utils.dart';
import 'package:df/widgets/toast_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:go_router/go_router.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:df/generated/l10n.dart';


class TestWebPage extends StatefulWidget {
  final String wechatUnionId;
  final String larkUnionId;
  final String userId;
  const TestWebPage({Key? key, required this.wechatUnionId, required this.larkUnionId, required this.userId}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    String url = Web.oldSpsUrl + Web.kWechatUnionId + Web.kEqual + wechatUnionId
        + Web.kAnd+ Web.kLarkUnionId + Web.kEqual + larkUnionId
        + Web.kAnd+ Web.kUserId + Web.kEqual + userId
        + Web.kAnd+ Web.kPlatform + Web.kEqual + Splash.vPlatform;
    LogUtils.w('【浏览器】最终地址= ' + url);
    return _TestWebPageState(url);
  }
}

class _TestWebPageState extends State<TestWebPage> {
  final String url;
  final String userUrl = 'https://sps.pheyma.com/wxhhapps/index.html#/langPage';
  _TestWebPageState(this.url);

  final GlobalKey webViewKey = GlobalKey();
  double progress = 0;
  final urlController = TextEditingController();
  PullToRefreshController? pullToRefreshController;
  InAppWebViewController? inAppWebViewController;


  @override
  void initState() {
    super.initState();

    pullToRefreshController = kIsWeb || ![TargetPlatform.iOS, TargetPlatform.android].contains(defaultTargetPlatform)
        ? null
        : PullToRefreshController(
      settings: PullToRefreshSettings(
        color: Colors.cyan,
      ),
      onRefresh: () async {
        if (defaultTargetPlatform == TargetPlatform.android) {
          inAppWebViewController?.reload();
        } else if (defaultTargetPlatform == TargetPlatform.iOS) {
          inAppWebViewController?.loadUrl(urlRequest: URLRequest(url: await inAppWebViewController?.getUrl()));
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return buildScaffold1(context);
  }

  Widget buildScaffold1(BuildContext context) {
    return

      Scaffold(
        appBar: AppBar(
            title: const Text('Web调试'),
            leading: IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: () {
                GoRouter.of(context).pop();
              },
            ),
            actions: [
              IconButton(
                icon: Icon(Icons.camera_alt),
                onPressed: () {

                  Future<PermissionStatus>? status = WebPage.requestCamera(PermissionKey.kCamera);
                  status?.then((permissionStatus) {
                    // 申请摄像头权限
                    if (permissionStatus.isGranted) {
                      ToastUtils.show(S.current.authorizedCamera);
                    } else {
                      LogUtils.e('(拒绝)相机权限');
                      ToastUtils.show(S.current.cameraPermissionDenied);
                    }
                  });

                },
              ),
            ]

        ),

        body: buildSafeArea2(context),
      );
  }

  Widget buildSafeArea2(BuildContext context) {
    return SafeArea(
      top: true,
      bottom: false,
      left: false,
      right: false,

      child: buildWillPopScope3(context),

    );
  }

  Widget buildWillPopScope3(BuildContext context) {
    bool _doubleBackToExitPressedOnce = false;

    return

      Column(children: <Widget>[
        ButtonBar(
          alignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              child: Icon(Icons.arrow_back),
              onPressed: () {
                inAppWebViewController?.goBack();
              },
            ),
            ElevatedButton(
              child: Icon(Icons.arrow_forward),
              onPressed: () {
                inAppWebViewController?.goForward();
              },
            ),
            ElevatedButton(
              child: Icon(Icons.home),
              onPressed: () {
                LogUtils.w("【点击事件】浏览器首页= ${url}");
                inAppWebViewController?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
                //webViewController?.reload();
              },
            ),
            ElevatedButton(
              child: Icon(Icons.manage_accounts),//manage_accounts//person//supervisor_account//people
              // child: Icon(Icons.home),
              onPressed: () {
                LogUtils.d("我的");
                inAppWebViewController?.loadUrl(urlRequest: URLRequest(url: WebUri(userUrl)));
              },
            ),
          ],
        ),

        Expanded(
          child: WillPopScope(
            onWillPop: () async {
              if (await inAppWebViewController?.canGoBack() ?? false) {
                inAppWebViewController?.goBack();
                return false;
              } else {
                if (_doubleBackToExitPressedOnce) {
                  return true;
                }
                _doubleBackToExitPressedOnce = true;
                ToastUtils.show(S.current.exitAgain);

                // 如果 2 秒内再次按下，则退出应用
                Future.delayed(Duration(seconds: 2), () {
                  _doubleBackToExitPressedOnce = false;
                });

                return false;
              }
            },
            child: buildStack4(context),
          ),
        ),
      ]);



  }

  Widget buildStack4(BuildContext context) {
    return Stack(
      children: [
        buildInAppWebView5(context),
        (progress < 1.0) ? LinearProgressIndicator(value: progress) : Container(),
      ],
    );
  }

  Widget buildInAppWebView5(BuildContext context) {
    final Completer<InAppWebViewController> controllerCompleter = Completer<InAppWebViewController>();

    return InAppWebView(
      //【JsFlutter-2/2】==============================================
      // initialData: InAppWebViewInitialData(data: htmlData),
      initialUrlRequest: URLRequest(url: WebUri('https://10.9.0.123:3000/')),
      // initialUrlRequest: URLRequest(url: WebUri('https://h5plugin.mumudev.top/#/pages/getQrcode/getQrcode')),
      // initialUrlRequest: URLRequest(url: WebUri('https://sps.pheyma.com/wxhhapps/index.html#/Mine/wxUnionId=ok-Ft6Fan2WipBocq_NzlK2Yy790&flyUnionId=on_4ef6c0235db38923b0d6002c5fa39f0a&userId=4660028360051142119&platform=android')),
      // initialUrlRequest: URLRequest(url: WebUri('https://www.jq22.com/yanshi18789')),
      //【JsFlutter-2/2】==============================================
      // 禁用 SSL 证书验证，总是信任
      onReceivedServerTrustAuthRequest: (controller, challenge) async {
        return ServerTrustAuthResponse(action: ServerTrustAuthResponseAction.PROCEED);
      },
      onConsoleMessage: (controller, consoleMessage) {
        LogUtils.d(
            '=============================================================================================================='
                '\n【Js控制台】\n${consoleMessage}\n'
            '=============================================================================================================='
        );
      },
      onWebViewCreated: (controller) async {
        inAppWebViewController = controller;
        controllerCompleter.complete(controller);
        controllerCompleter.future.then((value) {

        });
        WebPage.addJsHandler(context, controller);
      },
      initialUserScripts: UnmodifiableListView<UserScript>([]),
      key: webViewKey,
      pullToRefreshController: pullToRefreshController,
      // initialSettings: settings,
      initialSettings: kInAppWebViewSettings,
      onLoadStart: (controller, url) async {
        setState(() {
          urlController.text = url.toString();
          LogUtils.w('【浏览器】Url= ${url.toString()}');
        });
      },
      onPermissionRequest: (controller, request) async {
        return PermissionResponse(
            resources: request.resources,
            action: PermissionResponseAction.GRANT);
      },
      shouldOverrideUrlLoading:
          (controller, navigationAction) async {
        var uri = navigationAction.request.url!;
        if (![
          "http", "https", "file", "chrome", "data", "javascript", "about"
        ].contains(uri.scheme)) {
          if (await canLaunchUrl(uri)) {
            // Launch the App
            await launchUrl(
              uri,
            );
            // and cancel the request
            return NavigationActionPolicy.CANCEL;
          }
        }

        return NavigationActionPolicy.ALLOW;
      },
      onLoadStop: (controller, url) async {
        pullToRefreshController?.endRefreshing();
        setState(() {
          urlController.text = url.toString();
        });
        String? pageTitle = await controller.getTitle();
        LogUtils.w("【浏览器】标题= ${pageTitle}");
      },
      onReceivedError: (controller, request, error) {
        pullToRefreshController?.endRefreshing();
      },
      onProgressChanged: (controller, progress) {
        if (progress == 100) {
          pullToRefreshController?.endRefreshing();
        }
        setState(() {
          this.progress = progress / 100;
        });
      },
      onUpdateVisitedHistory: (controller, url, isReload) {
        setState(() {
          urlController.text = url.toString();
        });
      },
    );
  }

}

